// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// n [author] rhyme_lph
// l [email]  rhymelph@gmail.com
// s [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/a.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/current_subscription_entity.dart';
import 'package:finance_app/src/entities/plans_item_entity.dart';
import 'package:finance_app/src/provider/setting/subscription/sub_plans_provider.dart';
import 'package:finance_app/src/provider/setting/subscription_provider.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/widgets/button/normal_mini_2_button.dart';
import 'package:finance_app/src/widgets/common/tag_widget.dart';
import 'package:finance_app/src/widgets/common_tab_bar.dart';
import 'package:finance_app/src/widgets/list_item/sub_expandable_item.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';

class SubPlansView extends StatefulWidget {
  @override
  _SubPlansViewState createState() => _SubPlansViewState();
}

class _SubPlansViewState extends State<SubPlansView>
    with
        StatefulPresenter<SubPlansView, SubscriptionProvider,
            SubPlansProvider> {
  @override
  Widget buildWidget(BuildContext context) => DefaultTabController(
        length: 2,
        child: NestedScrollView(
          headerSliverBuilder: (context, value) {
            return [
              SliverToBoxAdapter(
                child: Column(
                  children: [
                    Column(
                      children: provider.topContents
                          .map(
                            (e) => SubExpandableItem(
                              header: Text(
                                e.title,
                                style: TextStyle(
                                    color: aceBlackColor,
                                    fontWeight: FontWeight.bold,
                                    fontSize: 15),
                              ),
                              expandedWidget: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: e.content
                                    .split('\\n')
                                    .map((text) => Padding(
                                          padding:
                                              const EdgeInsets.only(top: 10.0),
                                          child: Row(
                                            children: [
                                              Container(
                                                margin:
                                                    EdgeInsets.only(right: 15),
                                                child: SvgPicture.asset(
                                                  A.assetsImagesTick,
                                                  fit: BoxFit.contain,
                                                ),
                                              ),
                                              Expanded(child: Text(text)),
                                            ],
                                          ),
                                        ))
                                    .toList(),
                              ),
                            ),
                          )
                          .toList(),
                    ),
                    Stack(
                      alignment: Alignment.center,
                      children: [
                        Container(
                          width: getDp(325),
                          height: getDp(30),
                          decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(getDp(30)),
                              boxShadow: [
                                BoxShadow(
                                  color: Colors.black.withOpacity(0.25),
                                  blurRadius: getDp(3),
                                  spreadRadius: -getDp(1),
                                )
                              ]),
                        ),
                        CommonFillTabBar(
                          tabs: provider.tabs
                              .map((e) => MyTab(
                                    text: e,
                                  ))
                              .toList(),
                        ),
                      ],
                    ),
                  ],
                ),
              )
            ];
          },
          body: TabBarView(children: [
            listBuilder<int>(
              selector: (_, __) => __.monthlyList.length,
              builder: (BuildContext context, int value, Widget child) =>
                  _buildTabWidget(provider.monthlyList, false),
            ),
            listBuilder<int>(
              selector: (_, __) => __.annuallyList.length,
              builder: (BuildContext context, int value, Widget child) =>
                  _buildTabWidget(provider.annuallyList, true),
            ),
          ]),
        ),
      );

  Widget _buildTabWidget(List<PlansItemEntity> planList, bool hasPromotion) =>
      listBuilder<int>(
        selector: (_, __) => planList.length,
        builder: (BuildContext context, int value, Widget child) => ListView(
          children: [
            ...planList.map(
              (e) => buildItems(e, hasPromotion),
            ),
            if (hasPromotion && Config.currentSubscription.promos.length > 0)
              Column(
                children: [
                  ...Config.currentSubscription.promos.map(
                    (e) => Container(
                      margin:
                          EdgeInsets.symmetric(vertical: 15, horizontal: 20),
                      decoration: (BoxDecoration(
                        color: Colors.white,
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.25),
                            blurRadius: getDp(3),
                            spreadRadius: -getDp(1),
                          )
                        ],
                        borderRadius: BorderRadius.circular(10),
                      )),
                      child: Column(
                        children: [
                          Container(
                            padding: EdgeInsets.symmetric(vertical: 5),
                            decoration: BoxDecoration(
                              color: aceBlueColor,
                              borderRadius: BorderRadius.vertical(
                                  top: Radius.circular(10)),
                            ),
                            child: Center(
                              child: Text(
                                S.current.special_promotion,
                                style: TextStyle(color: Colors.white),
                              ),
                            ),
                          ),
                          Container(
                            padding: EdgeInsets.symmetric(horizontal: 10),
                            child: Row(
                              children: [
                                Container(
                                  width: 100,
                                  child: Text(e.title,
                                      textAlign: TextAlign.center,
                                      style: TextStyle(
                                          color: aceBlueColor,
                                          fontWeight: FontWeight.bold,
                                          fontSize: 17)),
                                ),
                                Padding(
                                  padding: const EdgeInsets.symmetric(
                                      horizontal: 10, vertical: 10),
                                  child: SvgPicture.asset(
                                      A.assetsImagesStyleVerticalDashed),
                                ),
                                Expanded(
                                  child: Text(e.content,
                                      style: TextStyle(
                                        color: aceBlackColor,
                                        fontSize: 15.5,
                                      )),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            AppSpaces.h20,
            Padding(
              padding: const EdgeInsets.only(left: 25.0),
              child: Text(S.current.upcoming_feature),
            ),
          ],
        ),
      );

  Widget buildItems(PlansItemEntity planList, bool hasPromotion) {
    return listBuilder<CurrentSubscriptionEntity>(
      selector: (_, __) => Config.currentSubscription,
      builder: (BuildContext context, CurrentSubscriptionEntity value,
              Widget child) =>
          value.plan.id == planList.id
              ? _buildSubItem(
                  onPressed: provider.onChangeStandard,
                  isSelect: value.isTrial == 0,
                  title: planList.nameText,
                  description: planList.description.split('\\n'),
                  assetPath: getImagePath(planList.name),
                  paid: planList.priceText,
                  maxRemaining: value.plan.transactionLimit ?? 0,
                  currentRemaining: value.plan.transactionCount ?? 0,
                  nextBillTime: value.subscription.plan.id == 1
                      ? null
                      : DateTimeUtils.toDateTime(
                          value.subscription.endAt, 'yyyy-MM-dd HH:mm:ss'),
                  onUpgrade: value.subscription.plan.id == 1
                      ? null
                      : () {
                          provider.onUpgrade(planList);
                        })
              : _buildSubItem(
                  onPressed: provider.onChangeStandard,
                  isSelect: false,
                  title: planList.nameText,
                  description: planList.description.split('\\n'),
                  assetPath: getImagePath(planList.name),
                  paid: planList.priceText,
                  maxRemaining: planList.transactionLimit,
                  currentRemaining: planList.transactionCount,
                  nextBillTime: null,
                  onUpgrade: () {
                    provider.onUpgrade(planList);
                  }),
    );
  }

  Widget _buildSubItem({
    VoidCallback onPressed,
    bool isSelect = false,
    String title,
    List<String> description,
    String assetPath,
    String paid,
    int maxRemaining,
    int currentRemaining,
    DateTime nextBillTime,
    VoidCallback onUpgrade,
  }) {
    bool isExpire = currentRemaining >= maxRemaining && isSelect == true;

    return SubExpandableItem(
      headerColor: aceWhiteBlue,
      expandedBorderColor: aceBlueColor,
      header: Row(
        children: [
          Text(
            title,
            style: TextStyle(
                color: aceBlackColor,
                fontWeight: FontWeight.w700,
                fontSize: 15),
          ),
          listBuilder<CurrentSubscriptionEntity>(
            selector: (_, __) => Config.currentSubscription,
            builder: (BuildContext context, CurrentSubscriptionEntity value,
                    Widget child) =>
                isSelect
                    ? Padding(
                        padding: const EdgeInsets.only(left: 15.0),
                        child: BlueTagWidget(
                          content: S.current.your_plan,
                        ),
                      )
                    : Container(),
          ),
          Expanded(
            child: Container(
              alignment: Alignment.centerRight,
              padding: const EdgeInsets.only(right: 15.0),
              child: Text(paid),
            ),
          ),
        ],
      ),
      expandedWidget: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: description
                  .map((text) => Padding(
                        padding: const EdgeInsets.only(top: 10.0),
                        child: Row(
                          children: [
                            Container(
                              width: getDp(4),
                              height: getDp(4),
                              margin: EdgeInsets.only(
                                right: getDp(11),
                              ),
                              decoration: BoxDecoration(
                                color: aceBlueColor,
                                shape: BoxShape.circle,
                              ),
                            ),
                            Expanded(child: Text(text)),
                          ],
                        ),
                      ))
                  .toList(),
            ),
          ),
          if (isSelect != true && onUpgrade != null)
            Padding(
              padding: const EdgeInsets.only(top: 12.0),
              child: NormalMini2Button(
                title: S.current.subscribe,
                onTap: onUpgrade,
              ),
            ),
        ],
      ),
    );
  }

  String getImagePath(String name) {
    switch (name) {
      case 'starting':
        return A.assetsImagesSettingBasic;
      case 'growing':
        return A.assetsImagesSettingUndrawAircraftFbvl_1;
      case 'established':
        return A.assetsImagesSettingPermium;
    }
    return null;
  }
}
